//
//  ST_BTSignOutViewController.swift
//  btvideo
//
//  Created by mac on 2020/4/22.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit

/**
 注销
 */
class ST_BTSignOutViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("注销账号")
        
        self.view.addSubview(signOutTitleLabel)
        signOutTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(15)
        }
        
        let strArray = ["1.无法登陆；",
                        "2.所有信息将被永久删除（头像、照片、特质等内容），你的配对对象无法再与你取得联系；",
                        "3.你的实名认证信息会解绑，解绑后可以再次绑定其他伴心账号；"]
        
        var lastLabel:UILabel?
        
        for str in strArray {

            let label = UILabel()
            label.numberOfLines = 0
            view.addSubview(label)
            
            let attrString = NSMutableAttributedString(string:str)
            
            let paragh = NSMutableParagraphStyle()
            
            paragh.lineSpacing = 5
                
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1),.paragraphStyle:paragh]
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            label.attributedText = attrString
            
            label.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.right.equalToSuperview().offset(-15)
                if let last = lastLabel{
                    make.top.equalTo(last.snp.bottom).offset(15)
                }else{
                    make.top.equalTo(signOutTitleLabel.snp.bottom).offset(15)
                }
            }
            lastLabel = label
        }
        
        
        view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-54)
            make.width.equalTo(260)
            make.height.equalTo(44)
        }
        
        RunLoop.current.add(self.timer, forMode: RunLoop.Mode.common)
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        self.timer.invalidate()
    }

//    MARK: -Properties
    fileprivate lazy var signOutTitleLabel:UILabel = {
        
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "注销后，你的账号将：")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        
        return label
    }()
    
    fileprivate var residueSeconds = 15
    
    fileprivate lazy var confirm_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("申请注销（15s）")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 15
        control.addTarget(self, action: #selector(confirm_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0.5
        return control
    }()
    
    fileprivate lazy var timer:Timer = {
       
        let tm = Timer.init(timeInterval: 1, target: self, selector: #selector(countDownHandle), userInfo: nil, repeats: true)
        
        return tm
    }()
    
}

//MARK: - Event
extension ST_BTSignOutViewController{
    
    @objc fileprivate func confirm_handle(){
        
        if confirm_btn.alpha < 0.8{
            return
        }
        
        
        
        self.navigationController?.pushViewController(SignOutInputController())
        
        
    }
    
    @objc fileprivate func countDownHandle(){
        
        residueSeconds -= 1
        
        if residueSeconds < 1{
            
            confirm_btn.setTitleForAllStates("申请注销")
            
            confirm_btn.alpha = 1
            
            timer.invalidate()
            
            return
        }
        
        confirm_btn.setTitleForAllStates("申请注销（\(residueSeconds)s）")
        
        
    }
    
    
    
}


//MARK: - Sign Out Input
class SignOutInputController: ST_BTLightBarViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    
        self.title_nav_btn.setTitleForAllStates("注销账号")
        
        view.addSubview(confirm_btn)
        confirm_btn.snp.remakeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-54+BTSafeAreaBottom-34)
            make.width.equalTo(260)
            make.height.equalTo(44)
        }
        
        view.addSubview(text_container_view)
        text_container_view.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(15)
            make.right.equalToSuperview().offset(-15)
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(162)
        }
        
        
        
        view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.edges.equalTo(text_container_view).inset(UIEdgeInsets.init(top: 15, left: 15, bottom: 15, right: 15))
        }
        
        view.addSubview(text_place_holder_label)
        text_place_holder_label.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(7)
            make.left.equalTo(textView).offset(5)
            make.right.equalTo(textView)
        }
        
        
        text_container_view.addSubview(current_text_count_label)
        current_text_count_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        view.addSubview(contact_label)
        contact_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(text_container_view.snp.bottom).offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        
        
        
    }
    
//    MARK: - Properties
    
    fileprivate lazy var confirm_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("提交")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 15
        control.addTarget(self, action: #selector(confirm_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0.5
        return control
    }()
    
    fileprivate lazy var text_container_view:UIView = {
       let control = UIView()
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var textView:UITextView = {
       let control = UITextView()
        control.backgroundColor = .clear
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.tintColor = UIColor.init(hex: 0x333333)
        control.delegate = self
        return control
    }()
    
    fileprivate lazy var text_place_holder_label:UILabel = {
       let control = UILabel()
        control.numberOfLines = 0
      
        let attrString = NSMutableAttributedString(string: "请填写不少于10字的注销理由（必填）")
        
        let param = NSMutableParagraphStyle()
        
        param.lineSpacing = 5
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1),.paragraphStyle:param]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        return control
    }()
    
    
    fileprivate lazy var contact_label:UILabel = {
       
        let control = UILabel()
        
        control.numberOfLines = 0
        
      let attrString = NSMutableAttributedString(string: "有了你的帮助，伴心会越来越好！希望你以后能再回来看看哟！")
      
      let param = NSMutableParagraphStyle()
      
      param.lineSpacing = 5
      
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor.init(hex: 0x333333)!,.paragraphStyle:param]
      
      attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
      
      control.attributedText = attrString
        
        return control
    }()
    
    fileprivate lazy var current_text_count_label:UILabel = {
       
        let control = UILabel()
        control.textColor = UIColor.init(hex: 0xACB4C0)
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "0/50"
        return control
        
    }()
    
    
    fileprivate let maxCount = 50
    
}

extension SignOutInputController{
    
    @objc fileprivate func confirm_handle(){
        
        
        if confirm_btn.alpha < 0.9{
            return
        }
        
        let param:[String:String] = ["reason":textView.text]
        
        self.show_indeterminate_h_u_d()
        
        
        JVrequest(PH.logoutResetApi,parameters:param ,success: { (json) in
            
            
            ToastHud(text: "注销账号成功", view: self.view)
            
            
            main_thread_execute(afterDelay: 1.5) {
                
                ST_BTUserInfoManager.shared.signOut()
                
                self.navigationController?.popToRootViewController(animated: true)
            }
            
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }
    
}


extension SignOutInputController:UITextViewDelegate{
    
    
    func textViewDidChange(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        guard var animal = textView.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: text)
            
//            var residueCount = maxCount - animal.count
//
//            if residueCount < 0{
//                residueCount = 0
//            }
            var displayCount = animal.count
            
            if displayCount > 50{
                displayCount = 50
            }
            
            current_text_count_label.text = "\(displayCount)/50"
//            counter_label.text = "还有\(residueCount)字"
            confirm_btn.alpha =  animal.count > 9 ? 1 : 0.5
            
            return animal.count <= maxCount
            
        }else{
            return true
        }
    }
    
}
